package cn.lizemin.web.common;

import cn.lizemin.web.annotation.RequestMapping;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author lzm
 * @Date 2024/10/5
 * @description 处理器映射器： 将url地址和唯一的handler进行映射（controller映射）
 */
public class HandlerMapping {

    /**
     * 保存url和处理器的映射规则
     */
    private final Map<String, Handler> mappings = new HashMap<>();

    /**
     * 根据url查找处理url的handler
     *
     * @param path 请求的url
     * @return 处理url的handler
     */
    public Handler getHandler(String path) {
        return mappings.get(path);
    }

    /**
     * 保存url和handler处理器的映射规则
     *
     * @param beans spring_mvc中所有定义的bean
     */
    public void process(List<Object> beans) {
        for (Object bean : beans) {
            for (Method method : bean.getClass().getDeclaredMethods()) {
                RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
                if (Objects.nonNull(requestMapping)) {
                    String url = requestMapping.value();
                    Handler handler = new Handler(bean, method);
                    mappings.putIfAbsent(url, handler);
                }
            }
        }
        System.out.println(mappings);
    }

}
